<template>
  <Teleport to="body">
    <div class="r-menu" :style="position" v-show="menuShow" id="right-menu">
      <div
        class="item"
        v-for="menu of menus"
        :key="menu.label"
        @click="sendClick(menu)"
      >
        <component :is="menu.icon" class="icon" />
        <span class="label">{{ menu.label }}</span>
      </div>
    </div>
  </Teleport>
</template>
<script setup>
import { computed, onBeforeMount, onMounted } from "vue";
import editStore from "@/store/editStore";
import {
  Delete,
  ArrowDown,
  ArrowUp,
  Upload,
  Download,
  Lock,
  Unlock,
} from "@element-plus/icons-vue";
let store = editStore();
let props = defineProps({
  position: {
    type: Object,
    default: () => ({ left: 0, top: 0 }),
  },
  menuShow: {
    type: Boolean,
    default: false,
  },
});

let emit = defineEmits(["menuClick", "update:menuShow"]);

let selectedComponent = computed(() => {
  return store.selectedComponent ?? {};
});
let lock = computed(() => {
  return selectedComponent.value?.lock ?? false;
});
let menus = computed(() => {
  let menu = [
    // { label: "置顶", event: "top", icon: Upload },
    // { label: "置底", event: "bottom", icon: Download },
    { label: "上移", event: "up", icon: ArrowUp },
    { label: "下移", event: "down", icon: ArrowDown },
    { label: "删除", event: "delete", icon: Delete },
  ];
  if (lock.value) {
    menu.unshift({
      label: "解锁",
      event: "unlock",
      icon: Unlock,
      mark: "lock",
    });
  } else {
    menu.unshift({ label: "锁定", event: "lock", icon: Lock, mark: "lock" });
  }
  return menu;
});

function sendClick(item) {
  switch (item.event) {
    case "lock":
      selectedComponent.value.lock = true;
      break;
    case "unlock":
      selectedComponent.value.lock = false;
      break;
    case "up":
      store.moveupComponent(selectedComponent.value);
      break;
    case "down":
      store.movedownComponent(selectedComponent.value);
      break;
    case "delete":
      store.deleteComponent(selectedComponent.value);
      break;
    default:
      break;
  }
  emit("update:menuShow", false);
}

onMounted(() => {
  document.body.addEventListener("click", handleClick);
});

function handleClick(e) {
  let node = e.target.closest("#right-menu");
  if (!node && props.menuShow) {
    emit("update:menuShow", false);
  }
}
onBeforeMount(() => {
  document.body.removeEventListener("click", handleClick);
});
</script>
<style scoped lang="scss">
.r-menu {
  position: fixed;
  width: 110px;
  padding: 5px 10px;
  z-index: 99999;
  background-color: rgb(72, 72, 78);
  border-radius: 5px;
  .item {
    width: 100%;
    height: 28px;
    display: flex;
    align-items: center;
    color: #eee;
    cursor: pointer;
    .icon {
      width: 16px;
      margin-right: 10px;
    }
    .label {
      font-size: 14px;
    }
  }
}
</style>
